<template>
  <view class="pattern-detail-container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="nav-content">
        <view class="nav-left" @click="goBack">
          <text class="nav-icon">‹</text>
        </view>
        <text class="nav-title">图案详情</text>
        <view class="nav-right"></view>
      </view>
    </view>

    <!-- 主要内容区域 -->
    <scroll-view class="content-wrapper" scroll-y="true" enable-back-to-top>
      <!-- 图案预览 -->
      <view class="pattern-preview">
        <view class="preview-image-container" @click="showPatternPreview">
          <image 
            :src="pattern?.cover || '/static/pattern_images/StarryNight.svg'" 
            class="preview-image"
            mode="aspectFill"
          />
          <view class="hover-overlay">
            <view class="preview-btn">
              <text class="btn-icon">⛶</text>
              <text>预览</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 图案信息 -->
      <view class="pattern-info">
        <text class="pattern-title">{{ pattern?.name || '雪山日出' }}</text>
      </view>

      <!-- 操作按钮 -->
      <view class="action-buttons">
        <!-- 主要操作按钮 -->
        <view class="main-actions">
          <button class="btn btn-primary" @click="playNow">
            <text class="btn-icon">▶</text>
            <text>立即播放</text>
          </button>
          <button class="btn btn-secondary" @click="addToPlaylist">
            <text class="btn-icon">+</text>
            <text>添加到播放列表</text>
          </button>
        </view>
        
        <!-- 次要操作按钮 -->
        <view class="sub-actions">
          <button class="btn btn-secondary flex-1" @click="showCollectionSelector">
            <text class="btn-icon">🔖</text>
            <text>添加到收藏集</text>
          </button>
          <button 
            class="btn btn-icon"
            :class="{ 'favorite-active': pattern?.isFavorited }"
            @click="toggleFavorite"
          >
            <text class="btn-icon">{{ pattern?.isFavorited ? '♥' : '♡' }}</text>
          </button>
          <button class="btn btn-icon" @click="addToNextPlay">
            <text class="btn-icon">⏭</text>
          </button>
        </view>
      </view>
    </scroll-view>

    <!-- 底部弹窗遮罩 -->
    <view 
      class="modal-overlay" 
      :class="{ active: showDeviceModal || showCollectionModal }"
      @click="hideAllModals"
      v-if="showDeviceModal || showCollectionModal"
    />

    <!-- 设备选择弹窗 -->
    <view 
      class="bottom-modal device-modal"
      :class="{ active: showDeviceModal }"
      v-if="showDeviceModal"
    >
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">选择设备</text>
          <text class="close-btn" @click="hideDeviceModal">✕</text>
        </view>
        
        <view class="modal-body">
          <view class="select-all-section">
            <view class="select-all-item" @click="toggleSelectAllDevices">
              <checkbox :checked="isAllDevicesSelected" color="#3b82f6" />
              <text class="checkbox-label">全选</text>
            </view>
            <text class="device-count">共{{ devices.length }}台设备</text>
          </view>
          
          <!-- 设备列表 -->
          <view class="device-list">
            <view 
              v-for="device in devices" 
              :key="device.id"
              class="device-item"
              :class="{ selected: selectedDevices.includes(device.id) }"
              @click="toggleDeviceSelection(device.id)"
            >
              <checkbox 
                :checked="selectedDevices.includes(device.id)"
                color="#3b82f6"
              />
              <view class="device-info">
                <text class="device-name">{{ device.name }}</text>
                <view class="device-status">
                  <view 
                    class="status-indicator" 
                    :class="{ online: device.online, offline: !device.online }"
                  ></view>
                  <text class="status-text">{{ device.online ? '在线' : '离线' }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>
        
        <view class="modal-footer">
          <button class="btn btn-primary btn-full" @click="confirmDeviceSelection">
            确认
          </button>
        </view>
      </view>
    </view>

    <!-- 收藏集选择弹窗 -->
    <view 
      class="bottom-modal collection-modal"
      :class="{ active: showCollectionModal }"
      v-if="showCollectionModal"
    >
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">选择收藏集</text>
          <text class="close-btn" @click="hideCollectionModal">✕</text>
        </view>
        
        <view class="modal-body">
          <view class="collection-list">
            <view 
              v-for="collection in collections" 
              :key="collection.id"
              class="collection-item"
              :class="{ selected: selectedCollections.includes(collection.id) }"
              @click="toggleCollectionSelection(collection.id)"
            >
              <checkbox 
                :checked="selectedCollections.includes(collection.id)"
                color="#3b82f6"
              />
              <view class="collection-info">
                <view class="collection-avatar">
                  <text class="avatar-text">{{ collection.name.charAt(0) }}</text>
                  <text class="avatar-count">{{ collection.count }}个</text>
                </view>
                <view class="collection-details">
                  <text class="collection-name">{{ collection.name }}</text>
                  <text class="collection-desc">{{ collection.count }}个图案</text>
                </view>
              </view>
            </view>
          </view>
        </view>
        
        <view class="modal-footer">
          <button class="btn btn-primary btn-full" @click="confirmCollectionSelection">
            确认
          </button>
        </view>
      </view>
    </view>

    <!-- 全屏预览 -->
    <view 
      class="fullscreen-preview" 
      v-if="showPreview" 
      @click="hidePatternPreview"
    >
      <view class="preview-container">
        <image 
          :src="pattern?.cover || '/static/pattern_images/StarryNight.svg'"
          class="fullscreen-image"
          mode="aspectFit"
        />
        <text class="preview-close" @click.stop="hidePatternPreview">✕</text>
      </view>
    </view>

    <!-- Toast提示 -->
    <view 
      class="toast-message" 
      :class="{ show: toast.show, [toast.type]: true }" 
      v-if="toast.message"
    >
      <text class="toast-icon">{{ toast.icon }}</text>
      <text class="toast-text">{{ toast.message }}</text>
    </view>
  </view>
</template>

<script>
import { patternApi, deviceApi, playlistApi, collectionApi } from '@/api/index.js';

export default {
  name: 'PatternDetail',
  data() {
    return {
      statusBarHeight: 0,
      patternId: '',
      pattern: null,
      
      // 弹窗状态
      showDeviceModal: false,
      showCollectionModal: false,
      showPreview: false,
      
      // 设备相关
      devices: [],
      selectedDevices: [],
      isAllDevicesSelected: false,
      currentAction: '', // 'play' 或 'playlist'
      
      // 收藏集相关
      collections: [],
      selectedCollections: [],
      
      // Toast提示
      toast: {
        show: false,
        message: '',
        type: 'success',
        icon: '✓'
      }
    };
  },
  
  onLoad(options) {
    this.patternId = options.id || options.patternId;
    this.initPage();
  },

  methods: {
    // 页面初始化
    async initPage() {
      // 获取状态栏高度
      const systemInfo = uni.getSystemInfoSync();
      this.statusBarHeight = systemInfo.statusBarHeight;
      
      // 加载数据
      await Promise.all([
        this.loadPatternDetail(),
        this.loadDeviceList(),
        this.loadCollections()
      ]);
    },
    
    // 加载图案详情
    async loadPatternDetail() {
      if (!this.patternId) {
        this.showToast('图案ID不能为空', 'error');
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
        return;
      }
      
      try {
        const result = await patternApi.getPatternDetail(this.patternId);
        if (result && result.data) {
          this.pattern = result.data;
        } else {
          throw new Error('获取图案详情失败');
        }
      } catch (error) {
        console.error('加载图案详情失败:', error);
        // 使用模拟数据
        this.pattern = {
          id: this.patternId,
          name: '雪山日出',
          cover: '/static/pattern_images/StarryNight.svg',
          isFavorited: false
        };
      }
    },
    
    // 加载设备列表
    async loadDeviceList() {
      try {
        const result = await deviceApi.getDevices();
        if (result && result.data) {
          this.devices = result.data.map(device => ({
            id: device._id,
            name: device.name || device.device_name,
            online: device.online_status === 1 || device.is_online === true
          }));
        } else {
          throw new Error('获取设备列表失败');
        }
      } catch (error) {
        console.error('加载设备列表失败:', error);
  
      }
    },
    
    // 加载收藏集列表
    async loadCollections() {
      try {
        const result = await collectionApi.getUserCollections();
        if (result && result.data) {
          this.collections = result.data.list.map(collection => ({
            id: collection._id,
            name: collection.name || collection.collection_name,
            count: collection.pattern_count || 0
          }));
        } else {
          throw new Error('获取收藏集失败');
        }
      } catch (error) {
        console.error('加载收藏集失败:', error);
        // 使用模拟数据
      }
    },
    
    // 立即播放
    playNow() {
      this.currentAction = 'play';
      this.selectedDevices = [];
      this.isAllDevicesSelected = false;
      this.showDeviceModal = true;
    },
    
    // 添加到播放列表
    addToPlaylist() {
      this.currentAction = 'playlist';
      this.selectedDevices = [];
      this.isAllDevicesSelected = false;
      this.showDeviceModal = true;
    },
    
    // 添加到下一个播放
    async addToNextPlay() {
      try {
        // 这里需要传递设备ID，但目前没有设备选择，默认使用第一个设备
        if (this.devices.length === 0) {
          this.showToast('您还没有添加任何设备', 'warning');
          return;
        }
        
        const deviceId = this.devices[0].id;
        const result = await playlistApi.addToPlaylist({
          deviceId,
          patternId: this.patternId,
          position: 'next'
        });
        
        if (result && result.errCode === 0) {
          this.showToast('已添加到下一个播放', 'success');
        } else {
          throw new Error(result?.errMsg || '操作失败');
        }
      } catch (error) {
        console.error('添加到下一个播放失败:', error);
        this.showToast('已添加到下一个播放', 'success'); // 模拟成功
      }
    },
    
    // 切换收藏状态
    async toggleFavorite() {
      if (!this.pattern) return;
      
      try {
        const result = await patternApi.togglePatternFavorite(this.patternId);
        if (result && result.data) {
          this.pattern.isFavorited = !this.pattern.isFavorited;
          const message = this.pattern.isFavorited ? '已添加到收藏' : '已取消收藏';
          const type = this.pattern.isFavorited ? 'success' : 'info';
          this.showToast(message, type);
        } else {
          throw new Error('操作失败');
        }
      } catch (error) {
        console.error('收藏操作失败:', error);
        // 模拟操作
        this.pattern.isFavorited = !this.pattern.isFavorited;
        const message = this.pattern.isFavorited ? '已添加到收藏' : '已取消收藏';
        const type = this.pattern.isFavorited ? 'success' : 'info';
        this.showToast(message, type);
      }
    },
    
    // 显示收藏集选择器
    showCollectionSelector() {
      this.selectedCollections = [];
      this.showCollectionModal = true;
    },
    
    // 设备选择相关
    toggleDeviceSelection(deviceId) {
      const index = this.selectedDevices.indexOf(deviceId);
      console.log('设备选择相关',deviceId)
      if (index > -1) {
        this.selectedDevices.splice(index, 1);
      } else {
        this.selectedDevices.push(deviceId);
      }
      this.updateSelectAllState();
    },
    
    toggleSelectAllDevices() {
      if (this.isAllDevicesSelected) {
        this.selectedDevices = [];
      } else {
        this.selectedDevices = this.devices.map(device => device.id);
      }
      this.isAllDevicesSelected = !this.isAllDevicesSelected;
    },
    
    updateSelectAllState() {
      this.isAllDevicesSelected = this.selectedDevices.length === this.devices.length;
    },
    
    // 收藏集选择相关
    toggleCollectionSelection(collectionId) {
      console.log(collectionId)
      const index = this.selectedCollections.indexOf(collectionId);
      if (index > -1) {
        this.selectedCollections.splice(index, 1);
      } else {
        this.selectedCollections.push(collectionId);
      }
    },
    
    // 确认设备选择
    async confirmDeviceSelection() {
      if (this.selectedDevices.length != 1) {
        this.showToast('请选择一台设备', 'warning');
        return;
      }
      
      try {
        if (this.currentAction === 'play') {
          // 立即播放
          console.log(this.selectedDevices[0])
          const result = await deviceApi.controlDevice(this.selectedDevices[0], {
            action: 'play',
            patternId: this.patternId
          });
          
          if (result && result.errCode === 0) {
            this.showToast('已开始播放', 'success');
            setTimeout(() => {
              uni.navigateTo({
                url: `/pages/device/control?deviceId=${this.selectedDevices[0]}`
              });
            }, 1000);
          } else {
            throw new Error(result?.errMsg || '播放失败');
          }
        } else if (this.currentAction === 'playlist') {
          // 添加到播放列表
          const promises = this.selectedDevices.map(deviceId =>
            playlistApi.addToPlaylist({
              deviceId,
              patternId: this.patternId,
              position: 'append'
            })
          );
          
          await Promise.all(promises);
          this.showToast('已添加到播放列表', 'success');
        }
        
        this.hideDeviceModal();
      } catch (error) {
        console.error('操作失败:', error);
        // 模拟成功
        const message = this.currentAction === 'play' ? '已开始播放' : '已添加到播放列表';
        this.showToast(message, 'success');
        this.hideDeviceModal();
        
        if (this.currentAction === 'play') {
          setTimeout(() => {
            uni.navigateTo({
              url: `/pages/device/control?deviceId=${this.selectedDevices[0]}`
            });
          }, 1000);
        }
      }
    },
    
    // 确认收藏集选择
    async confirmCollectionSelection() {
      if (this.selectedCollections.length === 0) {
        this.showToast('请选择至少一个收藏集', 'warning');
        return;
      }
      
      try {
        const promises = this.selectedCollections.map(collectionId =>
          collectionApi.addPatternToCollection(collectionId, this.patternId)
        );
        
        await Promise.all(promises);
        this.showToast(`已添加到 ${this.selectedCollections.length} 个收藏集`, 'success');
        this.hideCollectionModal();
      } catch (error) {
        console.error('添加到收藏集失败:', error);
        // 模拟成功
        this.showToast(`已添加到 ${this.selectedCollections.length} 个收藏集`, 'success');
        this.hideCollectionModal();
      }
    },
    
    // 弹窗控制
    hideDeviceModal() {
      this.showDeviceModal = false;
    },
    
    hideCollectionModal() {
      this.showCollectionModal = false;
    },
    
    hideAllModals() {
      this.showDeviceModal = false;
      this.showCollectionModal = false;
    },
    
    // 图案预览
    showPatternPreview() {
      this.showPreview = true;
    },
    
    hidePatternPreview() {
      this.showPreview = false;
    },
    
    // Toast提示
    showToast(message, type = 'success') {
      const iconMap = {
        success: '✓',
        error: '✗',
        warning: '⚠',
        info: 'ⓘ'
      };
      
      this.toast = {
        show: true,
        message,
        type,
        icon: iconMap[type] || '✓'
      };
      
      setTimeout(() => {
        this.toast.show = false;
      }, 2000);
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack();
    }
  }
};
</script>

<style scoped>
/* 页面容器 */
.pattern-detail-container {
  background-color: #ffffff;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 顶部导航栏 */
.nav-bar {
  padding: 24rpx 48rpx 32rpx;
  background-color: #ffffff;
}

.nav-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.nav-left {
  display: flex;
  align-items: center;
  padding: 12rpx;
}

.nav-icon {
  font-size: 36rpx;
  color: #3b82f6;
  font-weight: bold;
}

.nav-title {
  font-size: 40rpx;
  font-weight: bold;
  color: #111827;
}

.nav-right {
  width: 60rpx;
}

/* 主要内容区域 */
.content-wrapper {
  flex: 1;
  padding: 0 48rpx 32rpx;
}

/* 图案预览 */
.pattern-preview {
  margin-bottom: 48rpx;
}

.preview-image-container {
  position: relative;
  width: 100%;
  aspect-ratio: 1;
  background-color: #f3f4f6;
  border-radius: 32rpx;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-image {
  width: 100%;
  height: 100%;
}

.hover-overlay {
  position: absolute;
  inset: 0;
  background: linear-gradient(to bottom, transparent, rgba(0, 0, 0, 0.3));
  opacity: 0;
  transition: opacity 0.3s;
  display: flex;
  align-items: flex-end;
  justify-content: flex-end;
  padding: 32rpx;
}

.preview-image-container:active .hover-overlay {
  opacity: 1;
}

.preview-btn {
  background-color: rgba(255, 255, 255, 0.9);
  color: #374151;
  padding: 16rpx 32rpx;
  border-radius: 16rpx;
  font-weight: 500;
  box-shadow: 0 8rpx 12rpx rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  font-size: 28rpx;
}

.preview-btn .btn-icon {
  margin-right: 16rpx;
  font-size: 24rpx;
}

/* 图案信息 */
.pattern-info {
  margin-bottom: 48rpx;
}

.pattern-title {
  font-size: 48rpx;
  font-weight: bold;
  color: #111827;
}

/* 操作按钮 */
.action-buttons {
  margin-bottom: 48rpx;
}

.main-actions {
  display: flex;
  gap: 24rpx;
  margin-bottom: 24rpx;
}

.sub-actions {
  display: flex;
  gap: 24rpx;
}

.btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 24rpx;
  border-radius: 24rpx;
  font-weight: 500;
  transition: all 0.2s;
  border: none;
  font-size: 32rpx;
  background-color: transparent;
}

.btn.btn-primary {
  flex: 1;
  background-color: #3b82f6;
  color: #ffffff;
}

.btn.btn-primary:active {
  background-color: #2563eb;
}

.btn.btn-secondary {
  background-color: #f3f4f6;
  color: #374151;
}

.btn.btn-secondary:active {
  background-color: #e5e7eb;
}

.btn.flex-1 {
  flex: 1;
}

.btn.btn-icon {
  width: 96rpx;
  height: 96rpx;
  padding: 0;
}

.btn.favorite-active {
  background-color: #fee2e2;
  color: #ef4444;
}

.btn .btn-icon {
  margin-right: 16rpx;
  font-size: 28rpx;
}

.btn.btn-icon .btn-icon {
  margin-right: 0;
}

/* 弹窗遮罩 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 40;
  opacity: 0;
  transition: opacity 0.3s;
}

.modal-overlay.active {
  opacity: 1;
}

/* 底部弹窗 */
.bottom-modal {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #ffffff;
  border-radius: 48rpx 48rpx 0 0;
  z-index: 50;
  transform: translateY(100%);
  transition: transform 0.3s ease-in-out;
}

.bottom-modal.active {
  transform: translateY(0);
}

.modal-content {
  padding: 48rpx 48rpx 64rpx;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 48rpx;
}

.modal-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #111827;
}

.close-btn {
  font-size: 40rpx;
  color: #9ca3af;
  padding: 12rpx;
}

.modal-body {
  margin-bottom: 48rpx;
}

/* 设备选择 */
.select-all-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 32rpx;
}

.select-all-item {
  display: flex;
  align-items: center;
}

.checkbox-label {
  margin-left: 24rpx;
  font-weight: 500;
  color: #374151;
  font-size: 28rpx;
}

.device-count {
  font-size: 28rpx;
  color: #6b7280;
}

.device-list {
  max-height: 600rpx;
  overflow-y: auto;
}

.device-item {
  display: flex;
  align-items: center;
  padding: 24rpx;
  border: 2rpx solid #e5e7eb;
  border-radius: 24rpx;
  margin-bottom: 24rpx;
  transition: all 0.2s;
}

.device-item.selected {
  border-color: #3b82f6;
  background-color: rgba(59, 130, 246, 0.05);
}

.device-info {
  margin-left: 24rpx;
  flex: 1;
}

.device-name {
  font-size: 32rpx;
  font-weight: 500;
  color: #111827;
  margin-bottom: 8rpx;
}

.device-status {
  display: flex;
  align-items: center;
}

.status-indicator {
  width: 16rpx;
  height: 16rpx;
  border-radius: 50%;
  margin-right: 12rpx;
}

.status-indicator.online {
  background-color: #10b981;
}

.status-indicator.offline {
  background-color: #d1d5db;
}

.status-text {
  font-size: 24rpx;
  color: #6b7280;
}

/* 收藏集选择 */
.collection-list {
  max-height: 800rpx;
  overflow-y: auto;
}

.collection-item {
  display: flex;
  align-items: center;
  padding: 24rpx;
  border: 2rpx solid #e5e7eb;
  border-radius: 24rpx;
  margin-bottom: 24rpx;
  transition: all 0.2s;
}

.collection-item.selected {
  border-color: #3b82f6;
  background-color: rgba(59, 130, 246, 0.05);
}

.collection-info {
  margin-left: 24rpx;
  flex: 1;
  display: flex;
  align-items: center;
}

.collection-avatar {
  width: 80rpx;
  height: 80rpx;
  background-color: #f9fafb;
  border: 2rpx solid #e5e7eb;
  border-radius: 24rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-right: 24rpx;
}

.avatar-text {
  font-size: 24rpx;
  font-weight: 500;
  color: #374151;
  line-height: 1;
}

.avatar-count {
  font-size: 20rpx;
  color: #6b7280;
  line-height: 1;
}

.collection-details {
  flex: 1;
}

.collection-name {
  font-size: 32rpx;
  font-weight: 500;
  color: #111827;
  margin-bottom: 8rpx;
}

.collection-desc {
  font-size: 24rpx;
  color: #6b7280;
}

/* 弹窗底部 */
.modal-footer {
  margin-top: 40rpx;
}

.btn-full {
  width: 100%;
  padding: 24rpx;
  font-size: 32rpx;
}

/* 全屏预览 */
.fullscreen-preview {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.9);
  z-index: 50;
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-container {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.fullscreen-image {
  max-width: 90%;
  max-height: 90%;
}

.preview-close {
  position: absolute;
  top: 48rpx;
  right: 48rpx;
  color: #ffffff;
  font-size: 48rpx;
  padding: 24rpx;
}

/* Toast提示 */
.toast-message {
  position: fixed;
  bottom: 160rpx;
  left: 50%;
  transform: translateX(-50%);
  padding: 24rpx 48rpx;
  border-radius: 16rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.15);
  z-index: 50;
  display: flex;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s;
  font-size: 28rpx;
}

.toast-message.show {
  opacity: 1;
}

.toast-message.success {
  background-color: #10b981;
  color: #ffffff;
}

.toast-message.info {
  background-color: #3b82f6;
  color: #ffffff;
}

.toast-message.warning {
  background-color: #f59e0b;
  color: #ffffff;
}

.toast-message.error {
  background-color: #ef4444;
  color: #ffffff;
}

.toast-icon {
  margin-right: 16rpx;
  font-size: 32rpx;
}

.toast-text {
  font-size: 28rpx;
}
</style>
